package app.srong.service;

import app.srong.mapper.WordMapper;
import app.srong.vo.WordBean;
import app.srong.vo.WordExplains;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class WordService {


    @Autowired
    WordMapper wordMapper;

    @Autowired
    RestTemplate restTemplate;

    @Value("${trans.url}")
    private String url;

    @Autowired
    WordExplainsService wordExplainsService;


    public List<WordBean> getAllWord(Integer modeId){

        return wordMapper.getAllWord(modeId);
    }

    public List<WordBean> getWordByLen(Integer len) {

        return wordMapper.getWordByLen(len);
    }

    /**
     * 更新一个单词
     */
    public void updateOneWord() {
        WordBean word = wordMapper.getNoTransWord();

        if (word == null) {
            return;
        }

        JSONObject jsonObject = getJsonObject(word.getText());
        System.out.println(jsonObject);

        JSONArray translation = jsonObject.getJSONArray("translation");
        if (!translation.isEmpty()) {
            word.setDoc(translation.getString(0));
        }else {
            word.setDoc("翻译异常");
        }
        JSONObject basic = jsonObject.getJSONObject("basic");
        String basicString = basic.getString("us-phonetic");
        word.setBasic(basicString);

        wordMapper.update(word);


        if (basic.containsKey("explains")) {
            ArrayList<WordExplains> explains = new ArrayList<>();
            JSONArray array = basic.getJSONArray("explains");
            for (int i = 0; i < array.size(); i++) {
                WordExplains wordExplains = new WordExplains();

                String explain = array.getString(i);
                if (explain != null) {
                    String[] split = explain.split(". ");
                    if (split.length>1){
                        wordExplains.setWordId(word.getId());
                        wordExplains.setWordType(split[0]);
                        wordExplains.setExplains(split[1]);
                        wordExplains.setCreateTime(LocalDateTime.now());
                        wordExplains.setSource(1);
                        explains.add(wordExplains);
                    }
                }
            }

            wordExplainsService.save(explains);
        }



    }

    private JSONObject getJsonObject(String text) {
        String forObject = restTemplate.getForObject(url + text, String.class);
        System.out.println(forObject);
        return JSONObject.parseObject(forObject);
    }
}
